<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>H5页面</title>
</head>
<body>
<div>H5页面</div>
<button onclick="sendMessage()">发送消息到原生端</button>
<br>

<h2 id="msgContent" style="color: Orange; font-size: 20px;"></h2>
<script>
    // 全局通信端口
     var H5Port
     window.addEventListener("message", (event) => {
         if(event.data === "native_port") {
           H5Port = event.ports[0]
           if(H5Port) {
            H5Port.onmessage = (event) => {
               document.querySelector("#msgContent").innerText = event.data
            }
           }
         }
     })

     function sendMessage () {
      if(H5Port) {
          H5Port.postMessage("H5发送给原生消息")
      }
     }
</script>
</body>
</html>